<!--
 * @Description: 添加组件，蒙层对话框
 * @Author: youzi
 * @Date: 2020-05-20 14:11:14
 * @LastEditors: youzi
 * @LastEditTime: 2020-10-21 10:57:47
--> 
<template>
  <div>
    <modal
      :visible="visible"
      :title="addOrEdit === 0 ? '新增' : '编辑'"
      okText="保存"
      @cancelHandler="onClose"
      @okHandler="handleSubmit"
      :destroyOnClose="true"
      :width="600"
      :bodyHeight="0.8"
      :loading="loading"
    >
      <template slot="content">
        <!-- </div> -->
        <a-form :form="form">
          <a-form-item
            v-bind="formItemLayout"
            v-for="(item, index) in formItem"
            :key="index"
            :label="item.label"
            :extra="item.extra"
          >
            <a-radio-group
              v-if="item.type === 'radio'"
              :options="item.options"
              v-decorator="[
                item.decorator,
                {
                  initialValue:
                    initRecord[item.decorator] !== 'undefined' ? initRecord[item.decorator] : item.options[0].value,
                  rules: [{ required: item.required, message: `${item.label}不能为空` }]
                }
              ]"
            />
            <a-textarea
              v-else-if="item.type === 'textarea'"
              :rows="4"
              v-decorator="[
                item.decorator,
                {
                  rules: [
                    { required: item.required, message: `${item.label}不能为空` },
                    {
                      max: item.maxlen || 200,
                      message: `字数不能超过${item.maxlen || 200}字`
                    }
                  ],
                  initialValue: initRecord[item.decorator]
                }
              ]"
              :placeholder="`字数不能超过${item.maxlen || 200}字`"
            >
            </a-textarea>
            <a-input
              v-else
              style="width:100%;"
              :disabled="item.disabled"
              v-decorator="[
                item.decorator,
                {
                  initialValue: initRecord[item.decorator] || item.default,
                  rules: [{ required: item.required, message: `${item.label}不能为空` }]
                }
              ]"
            />
          </a-form-item>
        </a-form>
      </template>
    </modal>
  </div>
</template>
<script>
import moment from 'moment';
import modal from '~/tool/modal';
import { filterInputData } from 'utils/common';
// import {  DICT_CODE } from 'utils/business-enum';
import formItem from './form-data';

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 12 }
};

export default {
  name: 'add',
  components: { modal },
  props: {
    // 新增：0，编辑：1
    addOrEdit: {
      type: Number,
      default: 0
    },
    initRecord: {
      type: Object,
      default: () => ({})
    },
    visible: {
      default: false
    },
    // 需要的api
    apiURL: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      // 防抖函数的timer
      // timer: null,
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),

      // 需要提交的数据
      submitData: {},
      // formItem渲染列表
      formItem
    };
  },
  computed: {},
  methods: {
    moment,
    /**
     * @desc: 渲染selection
     * @author: youzi
     */ 
    reset() {
      this.$forceUpdate();
      this.loading = false;
    },
    onClose() {
      this.$confirm({
        title: '确定放弃编辑吗？',
        content: '',
        okText: '确定',
        cancelText: '取消',
        onOk: this.onCloseConfirm
      });
    },
    onCloseConfirm() {
      this.reset();
      this.$emit('close');
    },
    handleSubmit(close = true) {
      // debugger;
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$confirm({
            title: '确定保存吗？',
            content: '',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              this.handleConfirmSubmit(close);
              // return;
            }
          });
        }
      });
    },
    handleConfirmSubmit(close) {
      this.loading = true;
      let values = this.form.getFieldsValue();
      let tmpObj = {};
      let that = this;
      Object.keys(values).forEach((key, idx) => {
        if (filterInputData(values[key])) {
          if (typeof values[key] === 'string') {
            tmpObj[key] = values[key].trim();
          } else {
            tmpObj[key] = values[key];
          }
          // 对时间格式特殊化处理
          if (key.includes('Time')) {
            tmpObj[key] = values[key].format('YYYY-MM-DD');
          }
        }
      });
      console.log(tmpObj);
      let postUrl = this.addOrEdit === 0 ? this.apiURL.addRecords : this.apiURL.editRecords;
      let submitData = { ...tmpObj };
      if (this.addOrEdit !== 0) {
        submitData.id = this.initRecord.id;
      }
      this.$post(postUrl, { ...submitData })
        .then(r => {
          // this.reset();
          this.loading = false;
          if (close) {
            this.$emit('success');
          } else {
            this.form.resetFields();
          }
        })
        .catch(() => {
          this.loading = false;
        });
    }
  },
  mounted() {
  }
  /* watch: {
    visible(val) {
      debugger;
      if (val) {
        this.renderFileList();
      }
    }
  } */
};
</script>

<style lang="less" scoped>
.reason {
  color: rgba(0, 0, 0, 0.8);
  width: 85%;
  // width: 100%;
  margin-left: 10%;

  p {
    margin: 0;
  }
  .leader-opinion {
    font-size: 1rem;
  }
  .reject-reason {
    white-space: normal;
    font-size: 0.9rem;
  }
  .divider {
    margin-top: 10px;
  }
}
</style>